package be.xios.ti.droodle;

import java.io.*;

import org.xml.sax.*;
import org.xml.sax.helpers.*;

/**
 * @author student
 */
public class SAXLoader extends DefaultHandler {
	private File file;
	private Drawing drawing;
	
	public SAXLoader(File f) {
		this.file = f;
	}
	public void startDocument() throws SAXException {
		System.out.println("start parsing: "+file.getName());
		drawing = new Drawing();
	}
	
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		Shape s = null;
		try {
		if (qName.equals("drawing")) {
			String desc = attributes.getValue("description");
			drawing.setDescription(desc);
			String color = attributes.getValue("background");
			drawing.setBackground(XMLFormat.createColor(color));
		} else if (qName.equals("circle")) {
			s = new CircleShape();
			int r = Integer.parseInt(attributes.getValue("radius"));
			((CircleShape)s).setRadius(r);
		} else if (qName.equals("line")) {
			s = new LineShape();
			int x2 = Integer.parseInt(attributes.getValue("x2"));
			((LineShape)s).setX2(x2);
			int y2 = Integer.parseInt(attributes.getValue("y2"));
			((LineShape)s).setY2(y2);
		} else if (qName.equals("rectangle")) {
			s = new RectangleShape();
			int x2 = Integer.parseInt(attributes.getValue("x2"));
			((RectangleShape)s).setX2(x2);
			int y2 = Integer.parseInt(attributes.getValue("y2"));
			((RectangleShape)s).setY2(y2);
		}
		
		if (s != null) {
			String color = attributes.getValue("color");
			s.setColor(XMLFormat.createColor(color));
			int size = Integer.parseInt(attributes.getValue("size"));
			s.setSize(size);
			boolean filled = Boolean.valueOf(attributes.getValue("filled")).booleanValue();
			s.setFilled(filled);
			int x = Integer.parseInt(attributes.getValue("x"));
			s.setX(x);
			int y = Integer.parseInt(attributes.getValue("y"));
			s.setY(y);
			
			drawing.add(s);
		}
		} catch(Error err) {
			err.printStackTrace();
		}
	}
	
	/**
	 * @return Returns the drawing.
	 */
	public Drawing getDrawing() {
		return drawing;
	}
	
	/* (non-Javadoc)
	 * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException)
	 */
	public void error(SAXParseException e) throws SAXException {
		super.error(e);
		e.printStackTrace();
	}
	/* (non-Javadoc)
	 * @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException)
	 */
	public void fatalError(SAXParseException e) throws SAXException {
		super.fatalError(e);
		e.printStackTrace();
	}
	/* (non-Javadoc)
	 * @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException)
	 */
	public void warning(SAXParseException e) throws SAXException {
		super.warning(e);
		e.printStackTrace();
	}
}
